<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="queryParams.templateName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="分类" prop="category">
              <el-select v-model="queryParams.category" placeholder="分类" clearable>
                <el-option v-for="dict in template_category" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">

      <el-table v-loading="loading" border :data="templateMarketList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" width="70" label="序号" align="center" />
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="模板编号" align="center" prop="templateInfo.templateCode" />
        <el-table-column label="模板名称" align="center" prop="templateInfo.templateName" />
        <el-table-column label="打印类型" align="center" prop="templateInfo.printType.info" />
        <el-table-column label="分类" align="center" prop="templateInfo.category.info" />
        <el-table-column label="模板图片" align="center" prop="templateInfo.imageUrl">
          <template #default="scope">
            <image-preview :src="scope.row.templateInfo.imageUrl" width="90px" height="90px" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="模板路径" align="center" prop="templateInfo.templatePath" /> -->
        <!-- <el-table-column label="模板被采用次数" align="center" prop="templateInfo.usedCount" /> -->
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleFavorite(scope.row)"
              :icon="scope.row.isFavorite ? 'Star' : 'StarFilled'"
              :class="scope.row.isFavorite ? 'text-yellow-500' : ''">
              取消收藏
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改模板市场对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="templateMarketFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板编号" prop="templateCode">
          <el-input v-model="form.templateCode" placeholder="请输入模板编号" />
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="模板图片路径" prop="imageUrl">
          <el-input v-model="form.imageUrl" placeholder="请输入模板图片路径" />
        </el-form-item>
        <el-form-item label="模板路径" prop="templatePath">
          <el-input v-model="form.templatePath" placeholder="请输入模板路径" />
        </el-form-item>
        <el-form-item label="模板被采用次数" prop="usedCount">
          <el-input v-model="form.usedCount" placeholder="请输入模板被采用次数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TemplateMarket" lang="ts">
import {  getTemplateMarket, delTemplateMarket, addTemplateMarket, updateTemplateMarket, myCollectTemplateList, cancelCollectTemplate } from '@/api/templateMarket';
import { TemplateMarketVO, TemplateMarketQuery, TemplateMarketForm } from '@/api/templateMarket/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { template_category } = toRefs<any>(proxy?.useDict('template_category'));

const templateMarketList = ref<TemplateMarketVO[]>([]);
// 收藏状态映射
const favoriteMap = ref<Map<string | number, boolean>>(new Map());

// 初始化时从localStorage加载收藏状态
const loadFavoriteStatus = () => {
  const favorites = localStorage.getItem('templateFavorites');
  if (favorites) {
    try {
      const favoriteObj = JSON.parse(favorites);
      Object.entries(favoriteObj).forEach(([key, value]) => {
        favoriteMap.value.set(key, !!value);
      });
    } catch (e) {
      console.error('Failed to parse favorite status', e);
    }
  }
};

// 保存收藏状态到localStorage
const saveFavoriteStatus = () => {
  const favoriteObj: Record<string | number, boolean> = {};
  favoriteMap.value.forEach((value, key) => {
    favoriteObj[key] = value;
  });
  localStorage.setItem('templateFavorites', JSON.stringify(favoriteObj));
};
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const templateMarketFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TemplateMarketForm = {
  id: undefined,
  templateCode: undefined,
  templateName: undefined,
  printType: undefined,
  category: undefined,
  imageUrl: undefined,
  templatePath: undefined,
  usedCount: undefined
};
const data = reactive<PageData<TemplateMarketForm, TemplateMarketQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateCode: undefined,
    templateName: undefined,
    printType: undefined,
    category: undefined,
    imageUrl: undefined,
    templatePath: undefined,
    usedCount: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询模板市场列表 */
const getList = async () => {
  loading.value = true;
  const res = await myCollectTemplateList(queryParams.value);
  // 为每个模板添加收藏状态
  templateMarketList.value = res.rows.map((item: any) => ({
    ...item,
    isFavorite: favoriteMap.value.get(item.id) || false
  }));
  total.value = res.total;
  loading.value = false;
};

/** 处理取消收藏操作 */
const handleFavorite = async (row: any) => {
  // 如果未收藏，则不执行任何操作
  
  try {
    // 调用取消收藏接口
    await cancelCollectTemplate(row.id );
    
    // 更新本地状态
    row.isFavorite = false;
    favoriteMap.value.set(row.id, false);
    saveFavoriteStatus();
    
    // 显示操作成功提示
    proxy?.$modal.msgSuccess('取消收藏成功');

    getList();
  } catch (error) {
    console.error('Cancel favorite operation failed', error);
    proxy?.$modal.msgError('取消收藏失败，请重试');
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  templateMarketFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TemplateMarketVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加模板市场';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TemplateMarketVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTemplateMarket(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改模板市场';
};

/** 提交按钮 */
const submitForm = () => {
  templateMarketFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTemplateMarket(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTemplateMarket(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TemplateMarketVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除模板市场编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTemplateMarket(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/templateMarket/export',
    {
      ...queryParams.value
    },
    `templateMarket_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  loadFavoriteStatus();
  getList();
});
</script>
